bt.module({builder: function(bt) {
    var j$ = jQuery;
    var csrf = j$("#content").attr("data-csrf");
    var form = j$("#uploader-sns-form");
    var sns_type = j$("#content").attr("data-sns-type");
    var close_window = false;
    var next_url = j$("#content").attr("data-next-url");
    var page = 2;

    var _updateTripStatus = function () {
        var _url = form.attr("data-status");
        var _name = j$("#trip-name").val();
        var _privacy = j$("#trip-privacy").val();
        if ( _name === "" ) {
            j$("#trip-name").focus();
            j$("#trip-name-error").text("起个响亮的名字吧");
            return false;
        }
        j$.ajax({
            url: _url,
            type: 'POST',
            dataType: 'json',
            data: {
                "csrfmiddlewaretoken": csrf,
                "trip_name": _name,
                "privacy": _privacy
            },
        }).done(function(data) {
            if ( data.success ) {
                _uploadPhotos();
            }else{
                alert(data);
            }
        });
    };

    var _savePhoto = function ( a ) {
        if ( j$(a).hasClass("selected") ) {
            j$(a).removeClass("selected").find("span").text("选择照片");
        }else{
            if ( j$(a).attr("data-pk") === undefined ) {
                var _img = j$(a).find("img");
                var _url = form.attr("data-upload");
                var _id = j$(_img).attr("data-id");
                var _text = j$(_img).attr("data-text");
                var _lat = j$(_img).attr("data-lat");
                var _lng = j$(_img).attr("data-lng");
                var _picurl = j$(_img).attr("data-pic-url");
                var _privacy = j$(_img).attr("data-privacy");
                var _createdat = j$(_img).attr("data-created-time");
                j$.ajax({
                    url: _url,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        csrfmiddlewaretoken: csrf,
                        id: _id,
                        text: _text,
                        lat: _lat,
                        lng: _lng,
                        pic_url: _picurl,
                        privacy: _privacy,
                        created_time: _createdat
                    },
                    beforeSend: function(){
                        j$(a).removeClass("fail").attr("data-finished", 0).addClass("selected").find("span").text("取消选择");
                        j$("#uploader-sns-msg").show();
                        j$("#uploader-sns-done").addClass("uploader-sns-disable");
                    }
                }).done(function(data) {
                    if ( data.success ) {
                        _selectPhotos( a, data.pk );
                    }else{
                        j$(a).removeAttr("data-pk").removeAttr("data-finished").addClass("fail").removeClass("selected").find("span").text("重新上传");
                    }
                }).fail();
            }else{
                j$(a).attr("data-finished", 0).addClass("selected").find("span").text("取消选择");
            }
        }
    };

    var _refreshDoneButton = function() {
        j$("#uploader-sns-done").addClass("uploader-sns-disable");
        var photo_upload = false;
        var photos = j$("#filelist ul a[data-finished]");
        for (var i = 0; i < photos.length; i++) {
            if (j$(photos[i]).attr("data-finished") == "0") {
                photo_upload = true;
                break;
            }
        }
        if( !photo_upload && j$("#filelist ul a[data-pk]").length > 0 ) {
            j$("#uploader-sns-done").removeClass("uploader-sns-disable");
            j$("#uploader-sns-msg").hide();
            close_window = true;
        } else {
            j$("#uploader-sns-done").addClass("uploader-sns-disable");
            j$("#uploader-sns-msg").show();
            close_window = false;
        }
    };

    var _selectPhotos = function ( a, pk ) {
        j$(a).attr({
            "data-finished": 1,
            "data-pk": pk
        });
        _refreshDoneButton();
    };

    var _uploadPhotos = function () {
        var _btn = j$("#uploader-sns-done");
        var _loading = j$("#uploader-sns-msg");
        if( _btn.hasClass("uploader-sns-disable") ) {
            return false;
        }
        _btn.addClass("uploader-sns-disable");
        _loading.show();
        var data = {csrfmiddlewaretoken: csrf};
        var ids = [];
        j$("#filelist").find(".selected").each(function() {
            var _id = j$(this).attr("data-pk");
            if(_id) {
                ids.push(_id);
            }
        });
        data["pub_ids"] = ids;
        j$.ajax({
            url: _btn.attr("href"),
            type: "POST",
            data: data,
            success: function(resp) {
                if(!resp.error) {
                    j$(window.location).attr("href", resp.new_edit_link);
                } else {
                    // console.log(resp.error);
                    _btn.removeClass("uploader-sns-disable");
                    _loading.hide();
                }
            }
        });
        return false;
    };

    var _loadMorePhotos = function () {
        j$("#ajax-more").show();
        var _content = "";
        j$.ajax({
            url: "/sns/photos/",
            type: "GET",
            dataType: "json",
            data: {
                csrfmiddlewaretoken: csrf,
                sns_type: sns_type,
                page: page,
                next_page_url: next_url
            },
            success: function(resp) {
                if ( resp.success ) {
                    j$.each(resp.photos, function(index, val) {
                        _content += "<li><a title='"+val.text
                                 + "' href='###'><img class='t' src='"+val.thumbnail
                                 + "' data-id='"+val.id
                                 + "' data-pic-url='"+val.pic_url
                                 + "' data-created-time='"+val.created_time
                                 + "' data-text='"+val.text + "'";
                        if ( val.lat ) {
                            _content += " data-lat='"+val.lat
                                     + "' data-lng='"+val.lng
                                     + "' ><i class='l'></i";
                        }
                        _content += " ><i class='s'></i><b><span>选择照片</span></b></a></li>";
                    });
                    page = resp.page + 1;
                    next_url = resp.next_page_url;
                    j$(_content).appendTo("#filelist ul");
                    j$(".t").load(function() {
                        bt.misc.centerAlignImg(j$(this), 124, 124, false);
                    });
                    j$("#ajax-more").hide();
                }else{
                    j$("#load-more").hide();
                    // console.log( resp.msg );
                }
            }
        })
        .done(function(data) {
            // console.log(data);
        })
        .fail(function() {
            // console.log("error");
        })
        .always(function() {
            // console.log("complete");
        });
    };

    var _alertUnsavedChange = function () {
        if ( !close_window ) {
            return "您尚有未完成的操作，确定离开？";
        }
    };

    j$(document).ready(function() {
        j$(".t").each(function (argument) {
            bt.misc.centerAlignImg(j$(this), 124, 124, false);
        });
        j$(".t").load(function (argument) {
            bt.misc.centerAlignImg(j$(this), 124, 124, false);
        });
        j$("#filelist ul").on("click", "a", function() {
            _savePhoto( j$(this) );
        });

        j$("#uploader-sns-done").on("click", function(e) {
            e.preventDefault();
            _updateTripStatus();
        });

        j$("#uploader-sns-form").on("submit", function(e) {
            e.preventDefault();
            _updateTripStatus();
        });

        j$("#load-more").on("click", function() {
            _loadMorePhotos();
        });

        j$(window).on('beforeunload', function() {
            return _alertUnsavedChange();
        });
    });
}});

